package com.unicom.office.var;

import com.unicom.office.dataitem.DataItem;
import com.unicom.office.dataitem.ObjectDataItem;
import com.unicom.office.type.ObjectTypeItem;
import com.unicom.office.type.TypeItem;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ObjectVarItem extends VarItem {
    private ObjectTypeItem objType;

    public ObjectVarItem(String name, ObjectTypeItem objType) {
        super(name);
        this.objType = objType;
        this.setDefaultValue(new HashMap<String, Object>());
    }

    public TypeItem getTypeItem() {
        return objType;
    }

    public Object getFormatedValue(Object obj){
        Map<String, Object> map = null;
        if(obj == null){
            map = (Map<String, Object>)getDefaultValue();
        }else{
            map = (Map<String, Object>)obj;
        }

        // 对象的数据需要把属性也格式化
        Map<String, Object> newMap = new HashMap<String, Object>();
        Set<String> keySet = objType.getProps().keySet();
        for (String key : keySet) {
            Object formatedValue = objType.getProps().get(key).getFormatedValue(map.get(key));
            newMap.put(key, formatedValue);
        }

        return newMap;
    }

    public DataItem createDataItem(Object value) {
        return new ObjectDataItem(value, this);
    }

    public ObjectTypeItem getObjType() {
        return objType;
    }

    public DataItem getPropDataItem(Map map, String key){
        return objType.getProp(key).createDataItem(map.get(key));
    }
}
